package com.baidu.ueditor.define;

import java.util.HashMap;
import java.util.Map;

public class FileType {

    public static final String JPG = "JPG";
    public static final String JPEG = "JPEG";
    public static final String GIF = "GIF";
    public static final String PNG = "PNG";
    public static final String BMP = "BMP";
    public static final String ICON = "X-ICON";
    public static final String CSS = "CSS";
    public static final String JS = "JS";
    public static final String JAVASCRIPT = "JAVASCRIPT";
    public static final String HTML = "HTML";
    public static final String TXT = "TEXT";
    public static final String TEXT = "TEXT";

    private static final Map<String, String> types = new HashMap<String, String>();

    static {
        types.put(JPG, ".jpg");
        types.put(JPEG, ".jpg");
        types.put(GIF, ".gif");
        types.put(PNG, ".png");
        types.put(BMP, ".bmp");
        types.put(ICON, ".ico");
        types.put(CSS, ".css");
        types.put(JS, ".js");
        types.put(JAVASCRIPT, ".js");
        types.put(HTML, ".html");
        types.put("HTM", ".html");
        types.put(TXT, ".txt");
        types.put(TEXT, ".txt");
        types.put("PLAIN", ".txt");
    }

    public static String getSuffix ( String key ) {
        if (key == null || key.length() == 0) {
            return types.get( JPG );
        } else if (types.containsKey( key.toUpperCase() )) {
            return types.get( key.toUpperCase() );
        } else {
            return '.' + key.toLowerCase();
        }
    }

    /**
     * 获取文件扩展名<br>
     * /image/abc.def.png --&gt; .png<br>
     * /image/abcdef/png --&gt; null<br>
     * /image/abc.def/png --&gt; null<br>
     *
     * @param path 文件路径
     * @return 文件扩展名
     */
    public static String getExtension(String path) {
        return getExtension(path, true);
    }

    /**
     * 获取文件扩展名
     *
     * @param path 文件路径
     * @param dot 带不带点, 如true=.png, false=png
     * @return 文件扩展名
     */
    public static String getExtension(String path, boolean dot) {
        if (path == null) {
            return null;
        }

        int i = path.lastIndexOf('.');
        if (i < 0 || i < path.lastIndexOf('/') || i < path.lastIndexOf('\\')) {
            return null;
        }
        return path.substring(i + (dot ? 0 : 1)).toLowerCase();
    }

    /**
     * 清除文件扩展名<br>
     * /image/abc.def.png --&gt; /image/abc.def<br>
     * /image/abcdef/png --&gt; /image/abcdef/png<br>
     * /image/abc.def/png --&gt; /image/abc.def/png<br>
     *
     * @param path 原始路径
     * @return 新路径
     */
    public static String removeExtension(String path) {
        if (path == null) {
            return null;
        }

        int i = path.lastIndexOf('.');
        if (i < 0 || i < path.lastIndexOf('/') || i < path.lastIndexOf('\\')) {
            return path;
        }

        return path.substring(0, i);
    }

}
